/*
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
*/

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        // find largest k such as num[k] < num[k+1]
        int k, l, i = num.size()-1;
        if (i == 0) return; // no permutation if 1 elem
        // find first non-increasing instance
        while (i > 0 && num[i] <= num[i-1]) { i--; }
        if (i > 0) {
            k = i - 1;
            // find largest l such that num[k] < num[l]
            for (l = num.size()-1; l > k; l--) {
                if (num[k] < num[l]) {break;}
            }
            // swap num[k] and num[l]
            swap(num[k], num[l]);
        }
        // reverse num[i] till the end
        int first = i;
        int last = num.size()-1;
        while (first < last) {
            swap(num[first], num[last]);
            first ++; last --;
        }
    }
};
